/* eslint-disable default-case */
import { message } from 'antd';
import {
  getAccuList,
  getInsEmpNameList,
  getAccuEmpNameList,
  addInsRefundInfo,
  addAccuRefundInfo,
  getInsList,
  getInsEmpNameInfo,
  getInsRefundInfo,
  getAccuRefundInfo,
  getInsUpdateInfo,
  getAccuUpdateInfo,
  UpdateInsInfo,
  UpdateAccuInfo,
  execInvalidInsInfo,
  execInvalidAccuInfo,
  cancelInvalidInsInfo,
  cancelInvalidAccuInfo,
  getServiceDictList,
  getAccuEmpNameInfo,
  markData,
  alreadyPaidIns,
  alreadyPaidAccu,
  handleDicList,
  accumarkData,
  insUploadFile,
  accuUploadFile,
} from '@/services/fmManage';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';

const namespace = 'rebate';

export default {
  namespace,
  state: {
    activeKey: '1',
    formFieldsValue: {},
    pageData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    accuData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    // tabState:'1',
    selectedRows: [],
    selectedKeys: [],
    empNameList: [],
    insEmpNameInfo: {},
    accuEmpNameInfo: {},
    empBaseInfoVo: {},
    empSendInfoVo: {},
    insRefundInfo: {},
    accuRefundInfo: {},
    insUpdateVo: {},
    accuUpdateVo: {},
    serviceDictList: [],
    dataInfo: {},
    paymentList: [],
    resultInfo: {
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batNo: '', // 批次号
      errorParams: null, // 下载错误数据参数
    },
    showProgress: false,
    currentStep: 0,
    progressPercent: 0,
  },

  effects: {
    // 上传文件:批量进度
    uploadFileWithProgress: [
      function*({ payload }, { call, put }) {
        const { type, formData } = payload;
        let api;
        if (type === '1') {
          api = insUploadFile;
        } else {
          api = accuUploadFile;
        }
        const response = yield call(api, formData);
        if (response.success) {
          if (response.data && response.data.successProp !== 100) {
            const { batchId } = response.data;
            const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

            yield put.resolve({
              type: `socket/${SocketActions.subSocketChannel}`,
              payload: {
                batchTask,
              },
            });
          } else {
            yield put({
              type: 'updateBatchTask',
              payload: response.data,
            });
          }
        } else {
          // 上传失败
          message.warning(`${response.message || '上传失败'}`);
        }
        return response;
      },
      { type: 'throttle', ms: 10000 },
    ],
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.rebate);
      let { showProgress, resultInfo, currentStep } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        resultInfo.errorParams = {
          batNo: payload.batchId,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
    *fetchDicList({ payload }, { call, put }) {
      const response = yield call(handleDicList, payload);
      if (response.success) {
        yield put({
          type: 'dicList',
          payload: {
            data: response.data,
          },
        });
      }
    },
    *submitReceive({ payload }, { call }) {
      let res;
      if (+payload.activeKey === 1) {
        res = yield call(markData, payload.newSelectedRowKeys);
      } else {
        res = yield call(accumarkData, payload.newSelectedRowKeys);
      }
      return res;
    },
    *alreadyPaid({ payload }, { call }) {
      let res;
      if (+payload.activeKey === 1) {
        res = yield call(alreadyPaidIns, payload.newSelectedRowKeys);
      } else {
        res = yield call(alreadyPaidAccu, payload.newSelectedRowKeys);
      }
      return res;
    },
    *fetchInsList({ payload }, { call, put }) {
      const response = yield call(getInsList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getInsList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      }
    },
    *fetchAccuList({ payload }, { call, put }) {
      const response = yield call(getAccuList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      if (response.success) {
        yield put({
          type: 'getAccuList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      }
    },
    *fetchEmpNameList({ payload }, { call, select, put }) {
      const activekey = yield select(state => state.rebate.activeKey);

      const response = yield call(
        Number(activekey) === 1 ? getInsEmpNameList : getAccuEmpNameList,
        payload
      );
      if (response.success) {
        yield put({
          type: 'getEmpNameList',
          payload: response.data,
        });
      }
      return response;
    },
    // 获取详情信息
    *fetchInsEmpNameInfo({ payload }, { call, put }) {
      const response = yield call(getInsEmpNameInfo, payload);
      if (response.success) {
        yield put({
          type: 'getInsEmpNameInfo',
          payload: response.data,
        });
      }
    },
    *fetchAccuEmpNameInfo({ payload }, { call, put }) {
      const response = yield call(getAccuEmpNameInfo, payload);
      if (response.success) {
        yield put({
          type: 'getAccuEmpNameInfo',
          payload: response.data,
        });
      }
    },
    *addInsRefundInfo({ payload, callback }, { call }) {
      const response = yield call(addInsRefundInfo, payload);
      if (callback) {
        callback(response);
      }
    },
    *addAccuRefundInfo({ payload, callback }, { call }) {
      const response = yield call(addAccuRefundInfo, payload);
      if (callback) {
        callback(response);
      }
    },

    *fetchEmpNameInfo({ payload, callback }, { call }) {
      const response = yield call(addAccuRefundInfo, payload);
      if (callback) {
        callback(response);
      }
    },
    // 获取详情信息
    *fetchInsRefundInfo({ payload }, { call, put }) {
      const response = yield call(getInsRefundInfo, payload);
      if (response.success) {
        yield put({
          type: 'getInsRefundInfo',
          payload: response.data,
        });
      } else {
        message.warning(`${response.message || '服务器错误'}`);
      }
    },
    // 获取详情信息
    *fetchAccuRefundInfo({ payload }, { call, put }) {
      const response = yield call(getAccuRefundInfo, payload);
      if (response.success) {
        yield put({
          type: 'getAccuRefundInfo',
          payload: response.data,
        });
      } else {
        message.warning(`${response.message || '服务器错误'}`);
      }
    },

    // 获取社保修改详情信息
    *fetchInsUpdateInfo({ payload, callback }, { call, put }) {
      const response = yield call(getInsUpdateInfo, payload);
      if (callback) {
        callback(response);
      }
      if (response.success) {
        yield put({
          type: 'getInsUpdateInfo',
          payload: response.data,
        });
      }
    },

    // 获取公积金修改详情信息
    *fetchAccuUpdateInfo({ payload, callback }, { call, put }) {
      const response = yield call(getAccuUpdateInfo, payload);
      if (callback) {
        callback(response);
      }
      if (response.success) {
        yield put({
          type: 'getAccuUpdateInfo',
          payload: response.data,
        });
      }
    },

    // 社保修改
    *UpdateInsInfo({ payload, callback }, { call }) {
      const response = yield call(UpdateInsInfo, payload);
      if (callback) {
        callback(response);
      }
    },

    // 公积金修改
    *UpdateAccuInfo({ payload, callback }, { call }) {
      const response = yield call(UpdateAccuInfo, payload);
      if (callback) {
        callback(response);
      }
    },

    // 社保作废
    *execInvalidInsInfo({ payload, callback }, { call }) {
      const response = yield call(execInvalidInsInfo, payload);
      if (callback) {
        callback(response);
      }
    },
    // 公积金作废
    *execInvalidAccuInfo({ payload, callback }, { call }) {
      const response = yield call(execInvalidAccuInfo, payload);
      if (callback) {
        callback(response);
      }
    },

    // 社保取消作废
    *cancelInvalidInsInfo({ payload, callback }, { call }) {
      const response = yield call(cancelInvalidInsInfo, payload);
      if (callback) {
        callback(response);
      }
    },

    // 公积金取消作废
    *cancelInvalidAccuInfo({ payload, callback }, { call }) {
      const response = yield call(cancelInvalidAccuInfo, payload);
      if (callback) {
        callback(response);
      }
    },

    // 查询服务类型列表
    *fetchServiceDictList({ payload }, { call, put }) {
      const response = yield call(getServiceDictList, payload);
      if (response.success) {
        yield put({
          type: 'getServiceDictList',
          payload: response.data,
        });
      } else {
        yield put({
          type: 'getServiceDictList',
          payload: [],
        });
        message.warning(response.message);
      }
    },

    // 标记已支付
    *markModelData({ payload, callback }, { call }) {
      let response = null;
      if (+payload.activeKey === 1) {
        response = yield call(markData, payload.newSelectedRowKeys);
      } else {
        response = yield call(accumarkData, payload.newSelectedRowKeys);
      }

      if (callback) {
        callback(response);
      }
    },
  },

  reducers: {
    getAccuList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        accuData: { list, pagination: { total: data.totalCount, current: currentPage, pageSize } },
      };
    },
    getInsList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: { list, pagination: { total: data.totalCount, current: currentPage, pageSize } },
      };
    },
    getEmpNameList(state, { payload }) {
      const empData = Array.isArray(payload) ? payload : [];
      return {
        ...state,
        empNameList: empData,
      };
    },
    getInsEmpNameInfo(state, { payload }) {
      return {
        ...state,
        insEmpNameInfo: payload,
      };
    },
    getAccuEmpNameInfo(state, { payload }) {
      return {
        ...state,
        accuEmpNameInfo: payload,
      };
    },
    getInsRefundInfo(state, { payload }) {
      return {
        ...state,
        empBaseInfoVo: payload.empBaseInfoVo || {},
        empSendInfoVo: payload.empSendInfoVo || {},
        insRefundInfo: payload.insRefundInfo || {},
      };
    },
    getAccuRefundInfo(state, { payload }) {
      return {
        ...state,
        empBaseInfoVo: payload.empBaseInfoVo || {},
        empSendInfoVo: payload.empSendInfoVo || {},
        accuRefundInfo: payload.accuRefundInfo || {},
      };
    },
    // 获取社保编辑信息
    getInsUpdateInfo(state, { payload }) {
      return {
        ...state,
        insUpdateVo: payload,
      };
    },
    // 获取公积金编辑信息
    getAccuUpdateInfo(state, { payload }) {
      return {
        ...state,
        accuUpdateVo: payload,
      };
    },
    // 获取服务类型列表
    getServiceDictList(state, { payload }) {
      return {
        ...state,
        serviceDictList: payload,
      };
    },
    // 清空具体信息
    clearUpdateInfo(state) {
      return {
        ...state,
        insUpdateVo: {},
        accuUpdateVo: {},
        empNameList: [],
      };
    },
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    updatePagination(state, { payload }) {
      return {
        ...state,
        pageData: {
          list: [],
          pagination: {
            current: payload.current,
            pageSize: payload.pageSize,
          },
        },
      };
    },
    dicList(
      state,
      {
        payload: { data },
      }
    ) {
      return {
        ...state,
        paymentList: data.PAY_OBJ,
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: action.data,
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};
